import { defineStore } from "pinia";
import {ref} from "vue";
import loginApi from "../api/login.js";
import router from "../router/index.js";

function initStore() {
    return {
        name: "",
        username: "",
        user_id: 0,
        email: "",
        phone: "",
        token: "",
        refresh: "",
        exp: 0,
        nbf: 0,
        groupList: [],
        friendList: []
    }
}
export const useUserStore = defineStore("userStore", () => {
    const state = ref(initStore())

    // 保存token
    state.value.token = localStorage.getItem("token") || ""

    // 恢复用户信息
    async function restoreUser() {
        const token = localStorage.getItem("token")
        if (token) {
            try {
                const userInfo = await loginApi.checkToken(token)
                state.value.user_id = userInfo.data.user_id;
                state.value.username = userInfo.data.username;
                state.value.nbf = userInfo.data.nbf;
                state.value.exp = userInfo.data.exp;
            } catch (e) {
                // token无效，清理
                localStorage.removeItem("token")
                localStorage.removeItem("refresh")
                Object.assign(state.value, initStore())
                router.push('/login')
            }
        }
    }
    if (state.value.token) {
        restoreUser()
    }

    function logout() {
        localStorage.removeItem("token")
        localStorage.removeItem("refresh")
        Object.assign(state.value, initStore())
        router.push('/login')
    }
    console.log("init user store: ",state);
    return {
        state,
        restoreUser,
        logout
    }
})